document.addEventListener('DOMContentLoaded', function() {
    // Tab switching
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabPanes = document.querySelectorAll('.tab-pane');
    const tabsContainer = document.querySelector('.tabs');
    
    // 基础路径前缀 - 适配子路径部署
    const BASE_PATH = '/essay_helper';
    
    // Create sliding indicator
    const indicator = document.createElement('span');
    indicator.classList.add('tab-indicator');
    tabsContainer.appendChild(indicator);
    
    // Position indicator on initial active tab
    const activeTab = document.querySelector('.tab-btn.active');
    positionIndicator(activeTab);
    
    function positionIndicator(tab) {
        if (!tab) return;
        const tabRect = tab.getBoundingClientRect();
        const containerRect = tabsContainer.getBoundingClientRect();
        
        indicator.style.width = `${tabRect.width}px`;
        indicator.style.left = `${tabRect.left - containerRect.left}px`;
    }
    
    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            // Remove active class from all buttons and panes
            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.remove('active'));
            
            // Add active class to clicked button and corresponding pane
            button.classList.add('active');
            const tabId = button.getAttribute('data-tab');
            document.getElementById(tabId).classList.add('active');
            
            // Move indicator
            positionIndicator(button);
        });
    });
    
    // Window resize handler for indicator positioning
    window.addEventListener('resize', () => {
        positionIndicator(document.querySelector('.tab-btn.active'));
    });
    
    // File input label update with animation
    const fileInputs = document.querySelectorAll('input[type="file"]');
    fileInputs.forEach(input => {
        input.addEventListener('change', event => {
            const fileName = event.target.files[0]?.name || 'Choose PDF file';
            const label = input.nextElementSibling;
            
            // Add animation class
            label.classList.add('file-selected');
            
            // Update text with icon
            const icon = label.querySelector('i') ? label.querySelector('i').outerHTML : '';
            label.innerHTML = `${icon} ${fileName}`;
            
            // Remove animation class after animation completes
            setTimeout(() => {
                label.classList.remove('file-selected');
            }, 500);
        });
    });
    
    // Function to update progress bar
    function updateProgressBar(progressBar, value, text = null) {
        const progressElement = progressBar.querySelector('.progress-bar');
        progressElement.style.width = `${value}%`;
        
        if (text) {
            const textElement = progressBar.querySelector('.progress-text');
            textElement.textContent = text;
        }
    }
    
    // Function to simulate progress
    function simulateProgress(progressContainer, onComplete) {
        progressContainer.classList.remove('hidden');
        let progress = 0;
        const interval = setInterval(() => {
            progress += Math.random() * 15;
            if (progress >= 90) {
                progress = 90; // Cap at 90% while processing
                clearInterval(interval);
            }
            updateProgressBar(progressContainer, progress);
        }, 300);
        
        return {
            complete: () => {
                clearInterval(interval);
                updateProgressBar(progressContainer, 100, 'Complete!');
                setTimeout(() => {
                    progressContainer.classList.add('hidden');
                    if (onComplete) onComplete();
                }, 500);
            },
            error: (message) => {
                clearInterval(interval);
                updateProgressBar(progressContainer, 100, message || 'Error!');
                setTimeout(() => {
                    progressContainer.classList.add('hidden');
                }, 1000);
            }
        };
    }
    
    // Extract words form submission
    const extractForm = document.getElementById('extract-form');
    let extractedWords = []; // Store extracted words for download
    
    extractForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const fileInput = document.getElementById('extract-file');
        if (!fileInput.files[0]) {
            showNotification('请选择 PDF 文件', 'error');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', fileInput.files[0]);
        
        // Show loading spinner
        const spinner = document.querySelector('#word-results .loading-spinner');
        spinner.classList.remove('hidden');
        
        // Clear previous results
        const wordList = document.getElementById('word-list');
        wordList.innerHTML = '';
        
        // Hide download button
        const downloadBtn = document.getElementById('download-words-btn');
        downloadBtn.classList.add('hidden');
        
        // Hide add to vocabulary button if it exists
        const addToVocabBtn = document.getElementById('add-to-vocab-btn');
        if (addToVocabBtn) {
            addToVocabBtn.classList.add('hidden');
        }
        
        // Initialize progress bar
        const progressContainer = document.getElementById('extract-progress');
        const progressHandler = simulateProgress(progressContainer);
        
        try {
            const response = await fetch(`${BASE_PATH}/extract_words`, {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (response.ok) {
                // Complete progress
                progressHandler.complete();
                
                // Display the words with staggered animation
                if (!data.words || data.words.length === 0) {
                    const li = document.createElement('li');
                    li.textContent = '未找到新单词';
                    wordList.appendChild(li);
                } else {
                    showNotification(`找到 ${data.words.length} 个新单词`, 'success');
                    
                    // Store words for download
                    extractedWords = data.words;
                    
                    // Show download button
                    downloadBtn.classList.remove('hidden');
                    
                    // Create add to vocabulary button if not exists
                    if (!addToVocabBtn) {
                        const resultsHeader = document.querySelector('.results-header');
                        const addBtn = document.createElement('button');
                        addBtn.id = 'add-to-vocab-btn';
                        addBtn.className = 'action-btn';
                        addBtn.innerHTML = '<i class="fas fa-plus"></i> 添加到生词本';
                        addBtn.addEventListener('click', addWordsToVocabulary);
                        
                        // Insert after download button
                        resultsHeader.appendChild(addBtn);
                    } else {
                        addToVocabBtn.classList.remove('hidden');
                    }
                    
                    // Add words with staggered animation
                    data.words.forEach((word, index) => {
                        setTimeout(() => {
                            const li = document.createElement('li');
                            li.textContent = word;
                            li.style.opacity = '0';
                            li.style.transform = 'translateY(10px)';
                            wordList.appendChild(li);
                            
                            // Trigger animation
                            setTimeout(() => {
                                li.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                                li.style.opacity = '1';
                                li.style.transform = 'translateY(0)';
                            }, 10);
                        }, index * 50); // Stagger each word by 50ms
                    });
                }
            } else {
                progressHandler.error('失败');
                showNotification(`错误: ${data.error || '提取单词失败'}`, 'error');
            }
        } catch (error) {
            progressHandler.error('失败');
            showNotification('处理请求时发生错误', 'error');
            console.error(error);
        } finally {
            spinner.classList.add('hidden');
        }
    });
    
    // Add words to vocabulary function
    async function addWordsToVocabulary() {
        if (extractedWords.length === 0) {
            showNotification('没有单词可以添加', 'error');
            return;
        }
        
        // Disable the button during processing
        const addBtn = document.getElementById('add-to-vocab-btn');
        const originalText = addBtn.innerHTML;
        addBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 添加中...';
        addBtn.disabled = true;
        
        try {
            const response = await fetch(`${BASE_PATH}/add_to_vocabulary`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ words: extractedWords })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                showNotification(data.message || '单词已添加到生词本', 'success');
                
                // Clear extracted words after adding to vocabulary
                extractedWords = [];
                
                // Clear word list
                const wordList = document.getElementById('word-list');
                wordList.innerHTML = '';
                
                // Add success message
                const li = document.createElement('li');
                li.className = 'success-message';
                li.innerHTML = '<i class="fas fa-check-circle"></i> 单词已成功添加到生词本';
                wordList.appendChild(li);
                
                // Hide buttons
                document.getElementById('download-words-btn').classList.add('hidden');
                addBtn.classList.add('hidden');
            } else {
                showNotification(`错误: ${data.error || '添加单词失败'}`, 'error');
            }
        } catch (error) {
            showNotification('处理请求时发生错误', 'error');
            console.error(error);
        } finally {
            // Reset button
            addBtn.innerHTML = originalText;
            addBtn.disabled = false;
        }
    }
    
    // Download words button functionality
    const downloadWordsBtn = document.getElementById('download-words-btn');
    downloadWordsBtn.addEventListener('click', async () => {
        if (extractedWords.length === 0) {
            showNotification('没有单词可以下载', 'error');
            return;
        }
        
        try {
            // Send request to server to generate the file
            const response = await fetch(`${BASE_PATH}/download_words`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ words: extractedWords })
            });
            
            if (response.ok) {
                const blob = await response.blob();
                const url = URL.createObjectURL(blob);
                
                // Create temporary link and trigger download
                const a = document.createElement('a');
                a.href = url;
                a.download = 'unfamiliar_words.txt';
                document.body.appendChild(a);
                a.click();
                
                // Clean up
                setTimeout(() => {
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                }, 100);
                
                showNotification('单词下载成功', 'success');
            } else {
                const errorData = await response.json();
                showNotification(`错误: ${errorData.error || '下载单词失败'}`, 'error');
            }
        } catch (error) {
            showNotification('下载过程中发生错误', 'error');
            console.error(error);
        }
    });
    
    // Convert to audio form submission
    const audioForm = document.getElementById('audio-form');
    audioForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const fileInput = document.getElementById('audio-file');
        if (!fileInput.files[0]) {
            showNotification('请选择 PDF 文件', 'error');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', fileInput.files[0]);
        
        // Show loading spinner
        const spinner = document.querySelector('#audio-results .loading-spinner');
        spinner.classList.remove('hidden');
        
        // Hide audio player and file list
        const audioPlayer = document.getElementById('audio-player');
        audioPlayer.classList.add('hidden');
        
        // Clear existing audio files list if it exists
        const existingList = document.getElementById('audio-files-list');
        if (existingList) {
            existingList.innerHTML = '';
        }
        
        // Initialize progress bar
        const progressContainer = document.getElementById('audio-progress');
        const progressHandler = simulateProgress(progressContainer);
        
        try {
            const response = await fetch(`${BASE_PATH}/convert_to_audio`, {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (response.ok) {
                // Complete progress
                progressHandler.complete();
                
                if (data.audio_files && data.audio_files.length > 0) {
                    // 显示音频文件列表
                    displayAudioFiles(data.audio_files);
                    showNotification(data.message || '音频转换完成!', 'success');
                } else {
                    showNotification('未能生成音频文件', 'error');
                }
            } else {
                progressHandler.error('失败');
                showNotification(`错误: ${data.error || '转换音频失败'}`, 'error');
            }
        } catch (error) {
            progressHandler.error('失败');
            showNotification('处理请求时发生错误', 'error');
            console.error(error);
        } finally {
            spinner.classList.add('hidden');
        }
    });
    
    // 加载已有的音频文件列表
    async function loadAudioFiles() {
        try {
            const response = await fetch(`${BASE_PATH}/list_audio_files`);
            const data = await response.json();
            
            if (response.ok && data.audio_files && data.audio_files.length > 0) {
                // 切换到音频标签页
                const audioTab = document.querySelector('.tab-btn[data-tab="audio"]');
                audioTab.click();
                
                // 显示音频文件列表
                displayAudioFiles(data.audio_files);
            }
        } catch (error) {
            console.error('加载音频文件列表失败:', error);
        }
    }
    
    // 显示音频文件列表
    function displayAudioFiles(audioFiles) {
        const audioResults = document.getElementById('audio-results');
        
        // 检查是否已存在列表
        let audioList = document.getElementById('audio-files-list');
        if (!audioList) {
            // 创建列表容器
            audioList = document.createElement('div');
            audioList.id = 'audio-files-list';
            audioList.className = 'audio-files-list';
            
            // 添加标题
            const listTitle = document.createElement('h3');
            listTitle.innerHTML = '<i class="fas fa-list"></i> 可用音频文件';
            audioList.appendChild(listTitle);
            
            // 添加到结果区域
            audioResults.appendChild(audioList);
        } else {
            // 清空现有列表
            audioList.innerHTML = '';
            
            // 重新添加标题
            const listTitle = document.createElement('h3');
            listTitle.innerHTML = '<i class="fas fa-list"></i> 可用音频文件';
            audioList.appendChild(listTitle);
        }
        
        // 全局存储音频文件列表，供"播放全部"使用
        window.allAudioFiles = audioFiles;
        
        // 向列表添加音频文件
        audioFiles.forEach((audio, index) => {
            const audioItem = document.createElement('div');
            audioItem.className = 'audio-item';
            audioItem.dataset.index = index;
            
            // 音频名称和时长（如果有）
            const nameElem = document.createElement('div');
            nameElem.className = 'audio-name';
            
            // 显示格式：首词-尾词 (时长s)
            let displayName = `${audio.first_word}-${audio.last_word}`;
            if (audio.duration) {
                displayName += ` (${Math.round(audio.duration)}s)`;
            }
            
            nameElem.textContent = displayName;
            audioItem.appendChild(nameElem);
            
            // 音频控件
            const audioControls = document.createElement('div');
            audioControls.className = 'audio-controls';
            
            // 播放按钮
            const playButton = document.createElement('button');
            playButton.className = 'play-btn';
            playButton.innerHTML = '<i class="fas fa-play"></i>';
            playButton.addEventListener('click', () => {
                playAudioFile(audio, index);
            });
            audioControls.appendChild(playButton);
            
            // 下载按钮
            const downloadButton = document.createElement('a');
            downloadButton.className = 'download-btn';
            downloadButton.href = audio.audio_url;
            downloadButton.download = audio.file;
            downloadButton.innerHTML = '<i class="fas fa-download"></i>';
            audioControls.appendChild(downloadButton);
            
            audioItem.appendChild(audioControls);
            audioList.appendChild(audioItem);
        });
        
        // 设置播放全部按钮功能
        setupPlayAllButton();
    }
    
    // 播放特定的音频文件
    function playAudioFile(audio, index) {
        // 获取或创建音频播放器
        let player = document.getElementById('player');
        if (!player) {
            const audioPlayer = document.getElementById('audio-player');
            if (!audioPlayer) return;
            
            player = document.createElement('audio');
            player.id = 'player';
            player.controls = true;
            audioPlayer.appendChild(player);
        }
        
        // 同时显示播放器区域
        document.getElementById('audio-player').classList.remove('hidden');
        
        // 设置当前播放的索引
        window.currentPlayingIndex = index;
        
        // 高亮显示当前播放的项目
        highlightPlayingItem(index);
        
        // 设置播放源并播放
        player.src = audio.audio_url;
        
        // 更新下载链接
        const downloadLink = document.getElementById('download-link');
        if (downloadLink) {
            downloadLink.href = audio.audio_url;
            downloadLink.download = audio.file;
        }
        
        // 添加播放结束事件处理 - 自动播放下一个
        player.onended = () => {
            if (window.isPlayingAll && window.allAudioFiles && window.currentPlayingIndex < window.allAudioFiles.length - 1) {
                // 播放下一个文件
                const nextIndex = window.currentPlayingIndex + 1;
                playAudioFile(window.allAudioFiles[nextIndex], nextIndex);
            } else {
                window.isPlayingAll = false;
                updatePlayAllButton();
            }
        };
        
        player.play();
    }
    
    // 高亮显示当前播放的项目
    function highlightPlayingItem(index) {
        // 移除所有项目的高亮
        const items = document.querySelectorAll('.audio-item');
        items.forEach(item => {
            item.classList.remove('playing');
        });
        
        // 添加高亮到当前播放项目
        const currentItem = document.querySelector(`.audio-item[data-index="${index}"]`);
        if (currentItem) {
            currentItem.classList.add('playing');
        }
    }
    
    // 设置"播放全部"按钮功能
    function setupPlayAllButton() {
        const playAllBtn = document.getElementById('play-all-btn');
        if (!playAllBtn) return;
        
        playAllBtn.addEventListener('click', () => {
            if (window.isPlayingAll) {
                // 当前正在播放全部，停止
                window.isPlayingAll = false;
                
                // 如果有音频正在播放，暂停它
                const player = document.getElementById('player');
                if (player) {
                    player.pause();
                }
                
                updatePlayAllButton();
            } else {
                // 开始"播放全部"
                window.isPlayingAll = true;
                updatePlayAllButton();
                
                // 从第一个文件开始播放
                if (window.allAudioFiles && window.allAudioFiles.length > 0) {
                    playAudioFile(window.allAudioFiles[0], 0);
                }
            }
        });
        
        // 初始化按钮状态
        updatePlayAllButton();
    }
    
    // 更新"播放全部"按钮的状态
    function updatePlayAllButton() {
        const playAllBtn = document.getElementById('play-all-btn');
        if (!playAllBtn) return;
        
        if (window.isPlayingAll) {
            playAllBtn.innerHTML = '<i class="fas fa-pause-circle"></i> Pause All';
        } else {
            playAllBtn.innerHTML = '<i class="fas fa-play-circle"></i> Play All';
        }
    }
    
    // 初始化全局变量
    window.allAudioFiles = [];
    window.currentPlayingIndex = -1;
    window.isPlayingAll = false;
    
    // 页面加载完成后尝试加载音频文件列表
    loadAudioFiles();
    
    // Create notification container if it doesn't exist
    if (!document.getElementById('notification-container')) {
        const notificationContainer = document.createElement('div');
        notificationContainer.id = 'notification-container';
        document.body.appendChild(notificationContainer);
    }
    
    // Notification function
    function showNotification(message, type = 'info') {
        const container = document.getElementById('notification-container');
        
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        
        // Icon based on type
        let icon = '';
        switch (type) {
            case 'success':
                icon = '<i class="fas fa-check-circle"></i>';
                break;
            case 'error':
                icon = '<i class="fas fa-exclamation-circle"></i>';
                break;
            default:
                icon = '<i class="fas fa-info-circle"></i>';
        }
        
        notification.innerHTML = `${icon} <span>${message}</span>`;
        container.appendChild(notification);
        
        // Animate in
        setTimeout(() => {
            notification.classList.add('show');
        }, 10);
        
        // Automatically remove after 5 seconds
        setTimeout(() => {
            notification.classList.remove('show');
            notification.addEventListener('transitionend', function() {
                notification.remove();
            });
        }, 5000);
    }
}); 